import json
import time

from util.myredis import r
from views.base import BaseHandler
import tornado.websocket
import tornado.web

from db import db

conndict={}
class WebsockHandler(tornado.websocket.WebSocketHandler):
    # 跨域支持
    def check_origin(self, origin):
        return True
    #建立连接
    def open(self):
        #获取参数
        id = int(self.get_query_argument("id"))
        #存储链接
        conndict[id]=self
    #接收消息
    def on_message(self,mes):
        print(mes)

    def on_close(self):
        pass


class TTHandler(tornado.web.RequestHandler):
    def get(self):
        while True:
            id = int(self.get_query_argument('id'))
            print("id>>",id)
            wd = int(self.get_query_argument('wd'))
            print("wd",wd)
            r.str_add("keyss", wd)
            web = r.str_get('keyss')
            print(web)
            if web:
                key = int(web.decode())
                sql = "select * from web"
                res = db.findAll(sql)
                list = []
                for i in res:
                    if i['min'] <=key<=i['max']:
                        status = 1
                        list.append({'id':i['id'],'name':i['name'],'min':i['min'],'max':i['max'],'status':status,'wendu':key})
                    else:
                        status = 0
                        list.append({'id':i['id'],'name':i['name'],'min':i['min'],'max':i['max'],'status':status,'wendu':key})
                print("lst>>>>>",json.dumps(list))
                time.sleep(3)
                conndict[id].write_message(json.dumps(list))

class getweb(BaseHandler):
    def get(self):
        sql = "select * from web"
        res = db.findAll(sql)
        return self.finish({"code":200,"data":res})